package cn.pet_know.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

public class JWTUtil {
    private static final String secret = "haotchen"; // 将密钥设置为你的私密密钥


    private static String getSecret256Bit() {
        String base64Secret = Base64.getEncoder().encodeToString(secret.getBytes());
        base64Secret +=  base64Secret + base64Secret + base64Secret;
        return base64Secret;
    }

    /**
     * 获取token
     */
    public static String generateToken(Map<String, Object> data) {
        long expirationTime = 86400000; // 24小时，这里以毫秒为单位

        return Jwts.builder()
                .setHeaderParam("alg", "HS256")
                // 设置负载
                .setClaims(data)
                .setIssuer("haotchen@126.com")
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
                .signWith(SignatureAlgorithm.HS256, getSecret256Bit())
                .compact();
    }

    /**
     * 获取token负载中的内容
     *
     * @param token
     * @param targetOption
     * @return
     */
    public static String getUsernameFromToken(String token, String targetOption) {
        Claims body = Jwts.parser()
                .setSigningKey(getSecret256Bit())
                .parseClaimsJws(token)
                .getBody();
        Object val = body.get(targetOption);
        if (Objects.isNull(val)) {
            return "";
        } else {
            return val.toString();
        }
    }

    public static Date getTime(String token) {
        Date expiration = Jwts.parser()
                .setSigningKey(getSecret256Bit())
                .parseClaimsJws(token)
                .getBody().getExpiration();

        return expiration;
    }
}
